package org.sojex.photo.manage;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBManager
{

	static class mmarket{
		public static final String TableName="CACHE";	
		public static final String KEY_ROWId="id";
		public static final String KEY_IdKey="IdKey";//名字
		public static final String KEY_content="content";//
		public static final String KEY_date="date";
		
		public static final String[] columns=new String[]{KEY_ROWId,KEY_IdKey,KEY_content,KEY_date};
		public static final String Create_table=
			"create table "+TableName+"(id integer primary key autoincrement, "
			+KEY_IdKey+" text not null unique , "
			+KEY_content+" text not null,"
			+KEY_date+" Date not null "
			+");";
	}
	
	private static final String DATABASE_NAME = "PHOTO";
	private static final int DATABASE_VERSION = 3;


	private final Context context;

	private static  DatabaseHelper DBHelper=null;

	private static  SQLiteDatabase db=null;
	
	private static DBManager dbManager=null;

	private  DBManager(Context ctx) {
		this.context = ctx;
		DBHelper = new DatabaseHelper(context);
	}

	private static class DatabaseHelper extends SQLiteOpenHelper {
		public DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}
		public void onCreate(SQLiteDatabase db) {
				db.execSQL(mmarket.Create_table);
		}
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP TABLE IF EXISTS "+mmarket.TableName);
			onCreate(db);
		}
	}// DatabaseHelper

	// ---打开数据--
	public static  DBManager open(Context ctx) throws SQLException {
		if(dbManager!=null){

		}else{
			dbManager=new DBManager(ctx);
			db=DBHelper.getWritableDatabase();
		}
		return dbManager;
	}

	// ---关闭数据--
	public void close() {
		if(db!=null){
			db.close();
		}
		if(DBHelper!=null){
			DBHelper.close();
		}
		if(dbManager!=null){
			dbManager=null;
		}
	}
	//向表中插入条数据
	public void insertToCache(String IdKey,String content,String date){
		ContentValues cv=new ContentValues();
		cv.put(mmarket.KEY_IdKey, IdKey);
		cv.put(mmarket.KEY_content, content);
		cv.put(mmarket.KEY_date, date);
		
		Cursor cur=db.query(mmarket.TableName, mmarket.columns, 
				mmarket.KEY_IdKey+" LIKE ? ",new String[]{IdKey} ,null,null,null);
		if(cur!=null && cur.moveToFirst()){//已存在
			db.update(mmarket.TableName, cv, mmarket.KEY_IdKey+" LIKE ? ",new String[]{IdKey});
		}else{
			db.insert(mmarket.TableName,null, cv);
		}
		cur.close();
	}

	//检索IdKey表中的相应数据
	public Cursor getCache(String IdKey){
		return db.query(mmarket.TableName, mmarket.columns, 
				mmarket.KEY_IdKey+" LIKE ? ",new String[]{IdKey} ,null,null,null);
	}
}
